//
//  AdministratorViewController.m
//  PurchasingMeeting
//
//  Created by yanseng.lin on 3/24/14.
//  Copyright (c) 2014 YX. All rights reserved.
//

#import "AdministratorViewController.h"
#import "AppManager.h"
#import "WaitTooles.h"
#import "DataManager.h"
#import "ShopObject.h"
#import "PMGlobal.h"

@interface AdministratorViewController ()

@end

@implementation AdministratorViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setNavTitle:@"管理员"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *img = [[PMGlobal getInstance]getretimage];
    [b setImage:img forState:UIControlStateNormal];
    b.frame = CGRectMake(10, 10, img.size.width, img.size.height);
    [b addTarget:self action:@selector(ret) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithCustomView:b];
    self.navigationItem.leftBarButtonItem = left;
    
    UIImage *bgImage = [[UIHelper getInstance] getBundleImage:@"suit_bg.jpg"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:bgImage];
    
    UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 1024, 600)];
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        scroll.top = 64;
    }
    [self.view addSubview:scroll];
    
    img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    NSArray *arr = [[NSArray alloc]initWithObjects:@"更新基础资料",@"删除本地订单\n从服务器下载订单数据",@"全量上传订单",@"清除订单数据",@"重置订单", nil];
    int xinterval = 200;
    for (int i = 0; i < arr.count; i++) {
        int col = i % 4;
        int row = i / 4;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:img forState:UIControlStateNormal];
        [btn setTitle:[arr objectAtIndex:i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.adjustsFontSizeToFitWidth = YES;
        btn.titleLabel.textAlignment = UITextAlignmentCenter;
        btn.titleLabel.numberOfLines = 0;
        btn.frame = CGRectMake(0, 20, 180, 100);
        btn.left = 122+xinterval*col;
        btn.top = 30 + row * 120;
        btn.tag = 10+i;
        [scroll addSubview:btn]; 
    }
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidAppear:(BOOL)animated{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请输入管理员密码" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStyleSecureTextInput;
    alert.tag = 100;
    [alert show];
    [super viewDidAppear:animated];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag==100) {
        if (buttonIndex==1) {
            UITextField *tf = [alertView textFieldAtIndex:0];
            if ([tf.text isEqualToString:ADMIN_PASSWORD]) {
                
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else if (alertView.tag==101 && buttonIndex==1) {
        [self redownloadOrder];
    }else if(alertView.tag==102 && buttonIndex==1){
        [[DataManager sharedManager] copyDatabase];
        
        [[DataManager sharedManager] deleteTable:@"g_meeting"];
        [[DataManager sharedManager] deleteTable:@"s_user"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh" object:nil];
        showMessage(@"清除完毕");
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if (alertView.tag==100) {
//        if (buttonIndex==1) {
//            UITextField *tf = [alertView textFieldAtIndex:0];
//            if ([tf.text isEqualToString:@"000"]) {
//                
//            }else{
//                [self.navigationController popViewControllerAnimated:YES];
//            }
//            
//        }else{
//            [self.navigationController popViewControllerAnimated:YES];
//        }
//    }
//    else
//    {
////        if (buttonIndex==1) {
////            [self performSelector:@selector(redownloadOrder) withObject:nil afterDelay:0.5];
////        }
//    }
}

- (void)redownloadOrder{
    ShopObject *shopobj=[[DataManager sharedManager]getCurrentShop];
    if ([[DataManager sharedManager] getOrderedProducts:nil Shopid:shopobj.shopID Submit:0].count>0) {
        showMessage(@"您还有未上传订单，请先上传订单");
    }else{
        [WaitTooles showHUD:@"正在更新您的订单"];
        
        [[AppManager sharedManager] pauseAutoUpdateSession];
        [[AppManager sharedManager] pauseAutoSubmitSession];
        
        [[DataManager sharedManager] copyDatabase];
        
        [[DataManager sharedManager] deleteTableByShop:@"g_meeting" shop:shopobj.shopID];
        [[DataManager sharedManager] updateOrder:^(id res){
            
            showMessage(@"订单更新成功");
            [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh" object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh1" object:nil];
            [[AppManager sharedManager] resumeAutoUpdateSession];
            [[AppManager sharedManager] resumeAutoSubmitSession];
        }];
    }
}

-(void)ret
{
    UIImage *img = [[PMGlobal getInstance]getnavigationbarimage];
    [self.navigationController.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)btnClick:(UIButton *)sender
{
    switch (sender.tag) {
        case 10:
        {
            [[AppManager sharedManager] pauseAutoSubmitSession];
            [[AppManager sharedManager] pauseAutoUpdateSession];
            
            [WaitTooles showHUD:@"正在下载所有的商品资料，这个过程需要比较长的时间"];
            
            [[DataManager sharedManager] forceUpdate:^(id res){
                [WaitTooles removeHUD];
                [[AppManager sharedManager] resumeAutoSubmitSession];
                [[AppManager sharedManager] resumeAutoUpdateSession];
            }];
        }
            break;
        case 11:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"将会删除本机的所有订单数据，是否继续?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 101;
            [alert show];
        }
            break;
        case 12:
            [WaitTooles showHUD:@"提交订单"];
            [[AppManager sharedManager] forceSubmitAllOrder:^(id res){
                [WaitTooles removeHUD];
            }];
            break;
        case 13:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"将会删除本机的所有订单数据，是否继续?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 102;
            [alert show];
        }
            break;
        case 14:
        {
            [[DataManager sharedManager] clear];
        }
            break;
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
